package com.beney.messageHandler;

import com.beney.codec.MessagePacket;
import com.beney.message.MessageHandler;
import com.beney.message.bizz.ChatRedirectReq;
import com.beney.message.bizz.ChatSendResp;
import com.beney.message.bizz.ChatSendToOneReq;
import com.beney.server.ChannelManager;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ChatSendToOneReqHandler implements MessageHandler<ChatSendToOneReq> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ChannelManager channelManager;

    @Override
    public void handle(Channel ch, ChatSendToOneReq message) {
        // TODO: 错误处理

        ChatSendResp resp = new ChatSendResp()
                .setMsgId(message.getMsgId())
                .setCode(ChatSendResp.CODE_SUCCESS);
        ch.writeAndFlush(new MessagePacket(ChatSendResp.TYPE, resp));

        // 转发消息到指定用户
        ChatRedirectReq req = new ChatRedirectReq()
                .setMsgId(message.getMsgId())
                .setContent(message.getContent())
                .setToUser(message.getToUser())
                .setFromUser(message.getFromUser());
        channelManager.send(message.getToUser(), new MessagePacket(ChatRedirectReq.TYPE, req));
    }

    @Override
    public String messageType() {
        return ChatSendToOneReq.TYPE;
    }
}
